package com.jams.goodox.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hangzhou.jin.customview.SpaceItemDecoration;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.entity.GoodBuyBean;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.HomeService;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.NoScrollGridView;
import com.jams.goodox.widget.NoScrollListView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;
import com.jams.library.fresco.FrescoUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/10/1.
 */

public class OrderFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener{

    private static final String Fragment_Param = "isFromByPerson";
    @Bind(R.id.recycle_view)
    RecyclerView recycleView;
    @Bind(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;

    private String orderType;//订单类型

    private View rootView;

    private BaseQuickAdapter baseQuickAdapter;
    private List<OrderResp.DataBean> orderBeanList;

    private OrderResp orderResp;


    public static OrderFragment getInstance(String type) {
        OrderFragment findPassByCompanyFragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(Fragment_Param, type);
        findPassByCompanyFragment.setArguments(args);
        return findPassByCompanyFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) orderType = getArguments().getString(Fragment_Param);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(R.layout.order_list_fragment, container, false);
        ButterKnife.bind(this, rootView);
        init();
        getData();
        return rootView;
    }

    private void getData(){
        ProtocolManagers.getInstance().getService(HomeService.class).myOrder(SePref.getToken(),orderType).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                swipeRefresh.setRefreshing(false);
                try{
                    JsonObject jsonObject=response.body();
                    Gson gson = new Gson();
                    orderResp=gson.fromJson(jsonObject.toString(), OrderResp.class);
                    JsonArray jsonArray=jsonObject.getAsJsonArray("data");
                    for (int i=0,len=jsonArray.size();i<len;i++){
                        JsonObject jsonObjects=jsonArray.get(i).getAsJsonObject();
                        JsonArray productArray=jsonObjects.getAsJsonArray("product");
                        for(int z=0,lenz=productArray.size();z<lenz;z++){
                            JsonObject jsonObjectProduct=productArray.get(z).getAsJsonObject();
                            JsonArray jsonArray1=jsonObjectProduct.getAsJsonArray("option");
                            List<GoodBuyBean.Data.OptionBean> optionBeenList=new ArrayList<>();
                            for(int j=0,len1=jsonArray1.size();j<len1;j++){
                                JsonObject jsonElement=jsonArray1.get(j).getAsJsonObject();
                                String optionStr=jsonElement.toString();
                                String key=optionStr.split(":")[0].replace("\"","").replace("{","");
                                JsonObject b=jsonElement.getAsJsonObject(key);
                                Gson gson1=new Gson();
                                GoodBuyBean.Data.OptionBean optionBean=gson1.fromJson(b,GoodBuyBean.Data.OptionBean.class);
                                optionBean.setOptionKey(key);
                                optionBeenList.add(optionBean);
                            }
                            OrderResp.DataBean.ProductBean data= orderResp.getData().get(i).getProduct().get(z);
                            data.setOption(optionBeenList);
                            data.setAllMoney(StringUtils.stringToDouble(data.getPrice())*StringUtils.stringToDouble(data.getPrice()));
                        }
                    }
                    orderBeanList.clear();
                    orderBeanList.addAll(orderResp.getData());
                    baseQuickAdapter.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                swipeRefresh.setRefreshing(false);
            }
        });
    }

    private void init() {
        swipeRefresh.setOnRefreshListener(this);
        orderBeanList=new ArrayList<>();
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.addItemDecoration(new SpaceItemDecoration(DensityUtil.dp2px(getContext(),8)));
        baseQuickAdapter=new BaseQuickAdapter<OrderResp.DataBean>(R.layout.order_list_fragment_item,orderBeanList) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder,final OrderResp.DataBean item) {
                baseViewHolder.setText(R.id.tx_type,getType());
                baseViewHolder.setText(R.id.tx_order_money,String.format("共%s个产品 合计 ¥ %s",item.getNum(),item.getPayable()));
                baseViewHolder.setText(R.id.tx_order_number,item.getOrdersn());
                baseViewHolder.setText(R.id.tx_other,getDefaultStr());
                baseViewHolder.setVisible(R.id.tx_shanchu,"1".equalsIgnoreCase(orderType));
                baseViewHolder.setOnClickListener(R.id.tx_liucheng, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent in = new Intent(getActivity(), OrderFlowActivity.class);
                        in.putExtra("orderBean", item);
                        startActivity(in);
                    }
                });
                baseViewHolder.setOnClickListener(R.id.tx_shanchu, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doOrder(item,"delete");
                        ToastUtil.show("删除成功");
                    }
                });
                baseViewHolder.setOnClickListener(R.id.tx_other, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doDefaultClick(item);
                    }
                });

                NoScrollListView list_product=baseViewHolder.getView(R.id.list_product);
                setListViewAdapter(list_product,item.getProduct());
                baseViewHolder.setOnClickListener(R.id.tx_type, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent in=new Intent(getActivity(),OrderDetailActivity.class);
                        in.putExtra("orderBean",item);
                        startActivity(in);
                    }
                });
            }
        };
        recycleView.setAdapter(baseQuickAdapter);
    }

    private void doDefaultClick(OrderResp.DataBean dataBean){
        switch (orderType){
            case "1":
                if("押金支付".equalsIgnoreCase(dataBean.getPayType())){
                    ToastUtil.show("当前支付方式为押金支付，厂家正在确认，请等候厂家确认");
                    return;
                }
                doOrder(dataBean,"pay");
                break;
            case "2":
                Intent in=new Intent(getActivity(),OrderDetailActivity.class);
                in.putExtra("orderBean",dataBean);
                startActivity(in);
                break;
            case "3":
                doOrder(dataBean,"verify");
                break;
            case "4":
                Intent in1=new Intent(getActivity(),CommentActivity.class);
                in1.putExtra("orderBean",dataBean);
                startActivity(in1);
//                str="立即评价";
                break;
            case "5":
                doOrder(dataBean,"delete");
                ToastUtil.show("删除成功");
                break;
        }
    }

    private void doOrder(OrderResp.DataBean dataBean,String type){
        showLoading();
        enqueue(createCallService(HomeService.class).orderActive(SePref.getToken(),type, dataBean.getOrdersn(), new HashMap<String, String>()), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                misLoading();
                swipeRefresh.setRefreshing(true);
                onRefresh();
            }

            @Override
            public void onError(String msg) {
                misLoading();
                swipeRefresh.setRefreshing(true);
                onRefresh();
            }
        });
    }

    private String getDefaultStr(){
        String str="";
        switch (orderType){
            case "1":
                str="立即支付";
                break;
            case "2":
                str="订单详情";
                break;
            case "3":
                str="确认收货";
                break;
            case "4":
                str="立即评价";
                break;
            case "5":
                str="刪除订单";
                break;
        }
        return str;
    }

    private void setListViewAdapter(NoScrollListView listViewAdapter,List<OrderResp.DataBean.ProductBean> productInfoList){
        if(productInfoList==null)return;
        listViewAdapter.setAdapter(new ListCommonAdapter<OrderResp.DataBean.ProductBean>(getActivity(),productInfoList,R.layout.order_fragment_list_item) {
            @Override
            public void convert(ListCommonViewHolder helper,OrderResp.DataBean.ProductBean item, int position) {
                helper.setText(R.id.tx_order_code,item.getTitle());
                helper.setViewVisible(R.id.tx_time,false);
                helper.setText(R.id.tx_price_number,String.format("¥%s   *%s",item.getPrice(),item.getNum()));
                SimpleDraweeView sdv=helper.getView(R.id.sdv_product);
                FrescoUtil.loadNetUrl(sdv,item.getPreview());
                NoScrollGridView grid_good_ms=helper.getView(R.id.grid_good_ms);
                grid_good_ms.setFocusable(false);
                grid_good_ms.setAdapter(new ListCommonAdapter<GoodBuyBean.Data.OptionBean>(getActivity(),item.getOption(),R.layout.shop_type_item) {
                    @Override
                    public void convert(ListCommonViewHolder helper, GoodBuyBean.Data.OptionBean item, int position) {
                        helper.setText(R.id.tx_type,String.format("%s/%s",item.getOptionKey(),item.getName()));
                    }
                });
            }
        });
    }

    private String getType(){
        switch (orderType){
            case "1":
                return "待付款";
            case "2":
                return "待发货";
            case "3":
                return "待确认";
            case "4":
                return "待评价";
            case "5":
                return "已完成";
        }
        return "";
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        getData();
    }
}
